#!/usr/bin/env python
#coding: utf-8
'''
Created on 2017年4月21日

@author: Administrator
'''
from account import settings
from account.models import Profile
from celery.task import task
from common.decorators.celery import task_exception_handler
from common.utils import es
from common.utils.storage import save_url_by_fpath, exists
from elasticsearch.exceptions import TransportError
import logging
from django.contrib.auth.models import User
from common.core.contenttypes import fetch_content_type_id

# 为loggers中定义的名称
logger = logging.getLogger("celery")

@task
@task_exception_handler
def save_avatar_by_url(url, avatar_fpath, user_id):
    if not Profile.objects.filter(avatar_source_url=url, user_id=user_id).exists():
        if not exists(avatar_fpath):
            save_url_by_fpath(url, avatar_fpath)
        Profile.objects.filter(user_id=user_id).update(avatar_source_url=url, avatar_fpath=avatar_fpath)

@task
@task_exception_handler
def update_user_to_es_task(action):
    '''
    function: 
    '''
    #定义es
    try:
        es.es_client.index(settings.ES_INDEX_USER_LIST, doc_type=settings.ES_INDEX_USER_LIST_TYPE, body=action, id=action["id"])
        logger.info(u"update user to es by id %s success;" % action["id"]) 
    except TransportError:
        logger.warning(u"update user to es by id %s faild;" % action["id"]) 
        
